<template>
  <div style="display: inline-block" class="cy-upload">
    <el-upload :class="showBtnClass"
               :action="action||uploadUrl"
               list-type="picture-card"
               accept="image/*"
               :name="name"
               :headers="headers"
               :on-success="handleSuccess"
               :file-list="fileList"
               :limit="fileLimit"
               :multiple="!limit&&multiple"
               :before-upload="beforeUpload"
               :on-preview="handlePictureCardPreview"
               :on-progress="handleProgress"
               :on-error="handleError"
               :on-remove="handleRemove"
               :on-exceed="handleExceed"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <div v-if="loading" class="el-loading-mask" style="width:100%;height:100%;position:fixed;">
      <div class="el-loading-spinner" style="transform:translate(-40px,-20px);">
        <el-progress type="circle" :percentage="percentage"></el-progress>
        <p class="el-loading-text">上传中...</p></div>
    </div>
    <!--图片预览-->
    <el-dialog append-to-body :visible.sync="dialogVisible">
      <img :src="dialogImageUrl" style="width: 100%;" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import config from '../../config'
  import {getCookie} from '../../libs/cookie'

  export default {
    name: 'es-upload-img',
    props: {
      action: String,//上传地址
      // accept: String,//类型
      multiple: Boolean,//是否可上传多张
      name: String,
      value: [String, Array],//图片回显，多张图片用数组
      limit: Number,//上传数量
      size: Number//单个文件最大大小
    },
    data: function () {
      return {
        uploadUrl: config.uploadUrl,
        values: [],
        fileLimit: 100,
        fileList: [],
        currentIndex: 0,
        uploadNum: 0,
        sizeLimit: 0,
        showBtnClass: '',
        dialogImageUrl: '',
        dialogVisible: false,
        loading: false,
        headers: {token: getCookie('token')},
        percentage: 0,
      }
    },
    mounted: function () {
      this.fileLimit = this.multiple ? (this.limit ? this.limit : 100) : 1;
      this.sizeLimit = this.size ? this.size : 100;
      this.values = this.value || [];

      if (this.multiple) {
        for (let i = 0; i < this.values.length; i++) {
          this.values[i] && this.fileList.push({url: this.values[i]});
        }
      } else {
          this.value && this.fileList.push({url: this.value});
      }

      if (!this.multiple && this.values.length > 0) {
        this.showBtnClass = 'hide-upload-btn'
      } else {
        if (this.values.length >= this.fileLimit) {
          this.showBtnClass = 'hide-upload-btn'
        }
      }
    },
    watch: {
      values: function (val) {
        this.$emit('uploadSuccess', val)
      }
    },
    methods: {
      //图片上传成功
      handleSuccess (res, file) {
        if (res.code === 200) {
          let headPicArr = []
          if (!this.multiple) {
            headPicArr.push(res.url)
            this.showBtnClass = 'hide-upload-btn'
          } else {
            headPicArr = this.values
            headPicArr.push(res.url)
            if (headPicArr.length >= this.fileLimit) {
              this.showBtnClass = 'hide-upload-btn'
            }
          }
          this.values = headPicArr
          this.currentIndex++
          if (this.currentIndex === this.uploadNum) {
            this.percentage = 95
            let _this = this
            let time = setInterval(function () {
              _this.percentage++
              if (_this.percentage >= 100) {
                _this.loading = false
                _this.percentage = 0
                _this.currentIndex = 0
                _this.uploadNum = 0
                clearTimeout(time)
                _this.$message.success('上传成功')
              }
            }, 300)
          }
        }else{
          //上传失败
          this.$children[0].uploadFiles.splice(this.$children[0].uploadFiles.length-1,1);
          this.uploadNum++
          this.loading = false
          this.$message.error(res.msg);

        }
      },
      beforeUpload (file) {
        if (this.values.length >= this.fileLimit) {
          return false
        }
        // 文件大小限制
        const sizeLimit = file.size / 1024 / 1024 < this.sizeLimit
        if (!sizeLimit) {
          this.$message.error('上传的图片大小不能超过 ' + this.sizeLimit + 'MB!')
        }
        return sizeLimit
      },
      handleRemove (file, fileList) {
        let values = []
        for (let i = 0; i < fileList.length; i++) {
          values.push(fileList[i].url)
        }
        this.fileList = fileList;
        this.values = values
        this.showBtnClass = ''
      },
      handleProgress (event, file, fileList) {
        let _this = this
        _this.loading = true
        if (_this.uploadNum === 0) {
          let time = setInterval(function () {
            _this.percentage++
            if (_this.percentage === 95 || !_this.loading) {
              clearTimeout(time)
            }
          }, 1000)
        }
        _this.uploadNum++

      },
      handleExceed () {
        this.$message.error('最多只能上传' + this.fileLimit + '个文件!')
      },
      handleError () {
        this.$message.error("上传失败");
        this.loading = false
      },
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      }
    }
  }
</script>

<style scoped>

</style>
